package com.czk.aspect;

import com.czk.annotation.CzkTransaction;
import com.czk.transational.CzkTransactionManager;
import com.czk.transational.CzkTransactionType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/5 21:05
 */
@Aspect
@Component
@Order(1)
public class TransactionAspect  {
    /**
     * 自定义事务注解
     *
     * @param joinPoint
     */
    @Around("@annotation(com.czk.annotation.CzkTransaction)")
    public void invoke(ProceedingJoinPoint joinPoint) {
        System.out.println(Thread.currentThread().getName());
        // 拿到方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 拿到方法
        Method method = signature.getMethod();
        // 拿到注解
        CzkTransaction transaction = method.getAnnotation(CzkTransaction.class);
        // 定义全局事务id
        String groupId = "";
        if (transaction.isStart()) {
            // 事务开始
            // 创建全局事务id
            groupId = CzkTransactionManager.createLbTransactionGroup();
        } else {
            // 拿到分支事务
            groupId = CzkTransactionManager.getCurrentGroupId();
        }
        // 创建分支事务
        com.czk.transational.CzkTransaction czkTransaction = CzkTransactionManager.createLbTransaction(groupId);
        // 执行方法
        try {
            joinPoint.proceed();
            // 没有报错，添加提交事务
            CzkTransactionManager.addLbTransaction(czkTransaction, transaction.end(), CzkTransactionType.commit);
        } catch (Throwable throwable) {
            // 发生异常，设置回滚事务
            CzkTransactionManager.addLbTransaction(czkTransaction, transaction.end(), CzkTransactionType.rollback);
            throwable.printStackTrace();
        }

    }


}
